package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageBean;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
//@RestController
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;


    @Autowired
    private WebSocketServer webSocketServer;


    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;

    /**
     * 订单搜索
     *
     * @param orderPage
     * @return
     */
    @Override
    public PageBean searchOrder(OrdersPageQueryDTO orderPage) {
        PageHelper.startPage(orderPage.getPage(), orderPage.getPageSize());

        Page<Orders> page = orderMapper.pageQuery(orderPage);

        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page);

//
//        4.将订单Orders集合转换成OrderVO集合
//        List<Orders>  ------>  List<OrderVO>
//
//                5.封装PageResult，并返回


        return new PageBean(orderVOList, page.getTotal());

    }

    /**
     * 将Orders转化为OrderVO
     *
     * @param page
     * @return
     */
    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        //        3.遍历订单集合，查询每一个订单的订单明细：select * from order_detail where order_id=？
//        Orders   ------->   List<OrderDetail>
        ArrayList<OrderVO> orderVOS = new ArrayList<>();
        List<Orders> ordersList = page.getResult();
        if (ordersList != null && ordersList.size() > 0) {
            for (Orders orders : ordersList) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOS.add(orderVO);
            }
        }
        return orderVOS;
    }

    /**
     * 拼接菜品信息
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.selectOrder(orders.getId());
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getName() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    @Override
    public Integer countOrder(OrderPage orderPage) {
        Integer count = orderMapper.countOrder(orderPage.getBeginTime(), orderPage.getEndTime(), orderPage.getNumber(), orderPage.getStatus(), orderPage.getPhone());
        return count;
    }

    @Override
    public void deliveryOrder(String id) {
        Orders orderById = orderMapper.getOrderById(Long.valueOf(id));
        if (orderById != null && orderById.getStatus().equals(Orders.CONFIRMED)) {

            orderMapper.deliveryOrder(id);
        } else {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
    }

    @Override
    public void confirmOrder(TakeoutOrder takeoutOrder) {
        orderMapper.confirmOrder(takeoutOrder);
    }

    @Override
    public void rejectOrder(TakeoutOrder takeoutOrder) {
        orderMapper.rejectOrder(takeoutOrder);
    }

    @Override
    public TakeoutOrder getDetails(String id) {
        //1. 根据id查询订单
        Orders orderById = orderMapper.getOrderById(Long.valueOf(id));
        //2.判断订单只有存在且状态为2（待接单）才可以拒单
        if (orderById.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            TakeoutOrder order = orderMapper.getDetails(id);
            return order;
        } else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }


        //4.封装订单对象，设置订单状态、拒单原因、取消时间，修改订单数据
        //update  orders  set


    }

    @Override
    public void cancelOrder(OrdersCancelDTO takeoutOrder) {
        Orders orderById = orderMapper.getOrderById(takeoutOrder.getId());

        orderMapper.cancelOrder(takeoutOrder);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void completeOrder(String id) {
        Orders orderById = orderMapper.getOrderById(Long.valueOf(id));
        if (orderById != null && orderById.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {

            orderMapper.complete(id);
        } else {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
    }

    /**
     * 确认订单
     *
     * @return
     */
    @Override
    public Integer countConfirned() {
        return orderMapper.countConfirmed();
    }

    @Override
    public Integer countToBeConfirmed() {
        return orderMapper.countToBeConfirmeds();
    }

    @Override
    public Integer countDeliveryInProgress() {
        return orderMapper.countDeliveryInProgress();
    }

    //用户下单
    @Transactional
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //1.查询当前用户收货地址(校验收货地址是否为空）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);//
        }
        //2.查询当前用户的购物车数据（校验购物车是否为空）
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.select(ShoppingCart.builder().userId(BaseContext.getCurrentId()).build());
        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        // 判断用户收货地址是否超过5000
        //checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());// 地址
        //3.构造订单
        Orders orders = new Orders();
        orders.setUserId(BaseContext.getCurrentId());//订单属于用户
        orders.setNumber(UUID.randomUUID().toString());//订单号
        orders.setStatus(Orders.PENDING_PAYMENT);//待付款
        orders.setOrderTime(LocalDateTime.now());//下单时间
        orders.setPayStatus(Orders.UN_PAID);//支付状态 未支付

        orders.setPhone(addressBook.getPhone());//手机号
        orders.setAddress(addressBook.getDetail());//地址
        orders.setConsignee(addressBook.getConsignee());//收货人

        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        //4.向订单表插入1条数据
        orderMapper.insert(orders);
        //5.订单明细数据
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail od = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, od);
            od.setOrderId(orders.getId());// 主键返回
            orderDetails.add(od);
        }
        //6.向明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetails);
        //7.清理购物车中的数据
        shoppingCartMapper.deleteCart(BaseContext.getCurrentId());

        return OrderSubmitVO.builder().id(orders.getId()).orderTime(orders.getOrderTime()).orderAmount(orders.getAmount()).orderNumber(orders.getNumber()).build();
    }

    /**
     * 历史订单查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageBean ordersHistory(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        // 查询订单和订单明细
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());// 通过用户id查询
        // 分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);


        List<OrderVO> orderVOS = new ArrayList<>();
        // 查询
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                // 查询订单明细
                List<OrderDetail> odList = orderDetailMapper.selectOrder(orders.getId());// 通过order_id查询
                orderVO.setOrderDetailList(odList);
                orderVOS.add(orderVO);
            }
        }
        PageBean pageBean = new PageBean();
        pageBean.setRecords(orderVOS);
        pageBean.setTotal(page.getTotal());
        return pageBean;
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderById(Long id) {
        Orders orders = orderMapper.getOrderById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        List<OrderDetail> orderDetails = orderDetailMapper.selectOrder(id);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    public void cancelOrderById(Long id) {
        Orders orderById = orderMapper.getOrderById(id);
        //2.校验订单是否存在
        if (orderById == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //3.校验订单状态是否不允许进行取消（已接单/派送中/已完成/已取消）
        if (!orderById.getStatus().equals(Orders.PENDING_PAYMENT) || !orderById.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDERS_CANNOT_BE_CANCELLED);

        }

        //4.更新订单表数据：update orders  set
        orderMapper.cancelOrderById(id);

    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void postRepetitionById(Long id) {
        //        1.根据订单id查询当前订单详情
//        select * from order_detail where order_id = ?
//        List<OrderDetail>
        List<OrderDetail> orderDetails = orderDetailMapper.selectOrder(id);

//        2.将订单详情对象转换为购物车对象
//        List<OrderDetail>   ------>     List<ShoppingCart>
        List<ShoppingCart> shoppingCarts = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCarts.add(shoppingCart);
        }
//                3.将购物车对象批量添加到数据库：foreach
//        insert into shopping_cart  values
        shoppingCartMapper.insertBatchDish(shoppingCarts);
    }

    /**
     * 催单
     *
     * @param id
     */
    @Override
    public void getReminderById(Long id) {
        Orders orderById = orderMapper.getOrderById(id);
        if (orderById == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //2.基于websocket
        Map map = new HashMap();
        map.put("type", 2);//消息类型，1表示来单提醒 2表示催单
        map.put("orderId", orderById.getId());
        map.put("content", "麻溜点，接单吧");
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
    }


    /**
     * 检查客户的收货地址是否超出配送范围
     *
     * @param address 用户地址
     */
    private void checkOutOfRange(String address) {
        HashMap<String, String> map = new HashMap<>();
        map.put("address", shopAddress);
        map.put("output", "json");
        map.put("ak", ak);

        //获取店铺 经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/reverse_geocoding/v3", map);
        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if (jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("店铺解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");

        // 店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address", address);

        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/reverse_geocoding/v3", map);
        jsonObject = JSON.parseObject(userCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("货地址解析失败");
        }

        // 数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");

        // 用户收货地址
        String userLngLat = lat + "," + lng;

        map.put("origin", shopLngLat);
        map.put("destination", userLngLat);
        map.put("steps_info", "0");


        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if (distance > 5000) {
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }

    }
}
